package com.zxl.template.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.yhy.utils.core.SysUtils;
import com.yhy.utils.helper.PermissionHelper;
import com.zxl.template.R;
import com.zxl.template.activity.DeptAty;
import com.zxl.template.base.BaseFrag;
import com.zxl.template.base.IActivity;
import com.zxl.template.constant.constant;
import com.zxl.template.http.JsonCallback;
import com.zxl.template.model.Contact;
import com.zxl.template.model.ContactRows;
import com.zxl.template.model.Dept;
import com.zxl.template.model.MsgEvent;
import com.zxl.template.model.Test;
import com.zxl.zlibrary.tool.LActivityTool;
import com.zxl.zlibrary.tool.LEmptyTool;
import com.zxl.zlibrary.tool.LToast;
import com.zxl.zlibrary.tool.LogTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/*
 * @created by LoveLing on 2018/11/20
 * @emil 1079112877@qq.com
 * description:通讯录
 */
public class ContactFrag extends BaseFrag implements IActivity, constant {
    private static final String TAG = "ContactFrag";


    Unbinder unbinder;
    @BindView(R.id.tv_dept)
    TextView tvDept;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private String orgIds;

    public static BaseFrag getInstance() {
        return new ContactFrag();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_contact, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        requestPermissions();
        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
        initListener();
        //注册eventBus
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        mApi.contactList(this, orgIds, new JsonCallback<Contact>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogTool.e(TAG, e);
            }

            @Override
            public void onResponse(Contact contact, int i) {
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                recyclerView.setAdapter(new RvAdapter(contact.rows));
            }
        });
    }

    @Override
    public void initView() {
        if (LEmptyTool.isNotEmpty(mApi.mCurrentUser))
            orgIds = mApi.mCurrentUser.orgId;

    }


    @OnClick(R.id.tv_screen)
    public void onViewClicked() {
        LActivityTool.startActivity(DeptAty.class);
    }

    class RvAdapter extends BaseQuickAdapter<ContactRows, BaseViewHolder> {

        RvAdapter(@Nullable List<ContactRows> data) {
            super(R.layout.item_contact, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ContactRows item) {
            helper.setText(R.id.tv_name, item.userCnName);
            helper.setText(R.id.tv_dept, item.orgName);


            if (LEmptyTool.isNotEmpty(item.officeTel)) {
                helper.setVisible(R.id.tv_phone, true).setText(R.id.tv_phone, item.officeTel);

                helper.getView(R.id.tv_phone).setOnClickListener(v -> {
                    callPhone(item.officeTel);
                });
            }
            if (LEmptyTool.isNotEmpty(item.cellponeTel)) {
                helper.setVisible(R.id.tv_mobile, true).setText(R.id.tv_mobile, item.cellponeTel);
                helper.getView(R.id.tv_mobile).setOnClickListener(v -> {
                    callPhone(item.cellponeTel);
                });
            } else {
                helper.getView(R.id.tv_mobile).setVisibility(View.GONE);
            }

        }
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MsgEvent<List<Dept>> event) {
        if (event.type.equals(CONTACT_FRG_type)) {
            StringBuilder sb = new StringBuilder();
            for (Dept dept : event.t) {
                sb.append(",");
                sb.append(dept.id);
            }
            if (sb.length() > 0)
                sb.deleteCharAt(0);
            orgIds = sb.toString();

            initData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);

    }


    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Objects.requireNonNull(getActivity()).checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                // Permission has not been granted and must be
                // requested.

                if (shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE)) {

                }

                requestPermissions(
                        new String[]{Manifest.permission.CALL_PHONE},
                        1);
            } else {

            }
        }
    }
}
